package com.menker.app.webview;

import android.app.Activity;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.SystemClock;
import android.provider.CalendarContract;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.WebView;

import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.BridgeWebViewClient;
import com.menker.app.biz.ItemInfo;
import com.menker.app.common.ToolbarOwner;
import com.menker.app.common.Utils;
import com.menker.app.dao.ItemDAO;
import com.menker.app.ui.generalweb.GeneralWebViewActivity_;
import com.menker.app.util.IntentUtils;
import com.menker.app.util.TaobaoUtils;

import java.util.List;

/**
 * 在应用中加载页面
 *
 * @author J.Huang
 * @version 1.0
 */
public class GeneralWebViewClient extends BridgeWebViewClient {

    private Activity mActivity;
    private Fragment mFragment;
    private ToolbarOwner.IToolbar mToolbar;

    private BridgeWebView mWebView;

    private String qqKey = "";


    public GeneralWebViewClient(Fragment fragment,
                                ToolbarOwner.IToolbar toolbar,
                                String loadUrl,
                                BridgeWebView webView) {
        super(webView);
        mFragment = fragment;
        mToolbar = toolbar;
        mActivity = fragment.getActivity();
        mWebView = webView;
    }

    public GeneralWebViewClient(Activity activity,
                                ToolbarOwner.IToolbar toolbar,
                                String loadUrl,
                                BridgeWebView webView) {
        super(webView);
        mActivity = activity;
        mToolbar = toolbar;
        mFragment = null;
        mWebView = webView;
    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);
        String lowerCaseUrl = url.toLowerCase().trim();
        if (TaobaoUtils.isItemDetailsLink(lowerCaseUrl)) {
            Uri uri = Uri.parse(lowerCaseUrl);
            String itemId = uri.getQueryParameter("id");
            if (mActivity instanceof GeneralWebViewActivity_) {
                if (lowerCaseUrl.contains("mm_")) {
                    ((GeneralWebViewActivity_) mActivity).enableItemSharing(itemId);
                }
            }
        } else if (lowerCaseUrl.startsWith("http://") || lowerCaseUrl.startsWith("https://")) {
            if (mActivity instanceof GeneralWebViewActivity_) {
                ((GeneralWebViewActivity_) mActivity).disableItemSharing();
            }
        }
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
         if (url == null || TextUtils.isEmpty(url)) {
            return true;
        }
//
//        if (mClearHistoryFlag) {
//            view.clearHistory();
//            mClearHistoryFlag = false;
//        }

        String lowerCaseUrl = url.toLowerCase().trim();

        if (lowerCaseUrl.startsWith("mqqopensdkapi://")) {
            IntentUtils.toJoinQQGroupActivity(mActivity, "mqqopensdkapi://bizAgent/qm/qr?url=http%3A%2F%2Fqm.qq.com%2Fcgi-bin%2Fqm%2Fqr%3Ffrom%3Dapp%26p%3Dandroid%26k%3D" + "eC8YTYGr3VUvjQs3f-Xc0frZqNDVaVjT");
        }

        if (lowerCaseUrl.contains("/invite/app.html")) {
            IntentUtils.toMainActivity(mActivity);
            return true;
        }

        if (TaobaoUtils.isItemDetailsLink(lowerCaseUrl)) {
            Uri uri = Uri.parse(lowerCaseUrl);
            String itemId = uri.getQueryParameter("id");

            if (mActivity instanceof GeneralWebViewActivity_) {
//                mToolbar.setToolbarTitle("商品详情");
                if (lowerCaseUrl.contains("mm_")) {
                    ((GeneralWebViewActivity_) mActivity).enableItemSharing(itemId);
                }
            }
        } else if (TaobaoUtils.isInvalidLink(lowerCaseUrl)) {
            return true;
        } else if (lowerCaseUrl.startsWith("http://") || lowerCaseUrl.startsWith("https://")) {
            if (mActivity instanceof GeneralWebViewActivity_) {
                ((GeneralWebViewActivity_) mActivity).disableItemSharing();
            }
        }

//        // 放在所有特殊操作之后，因为url中可能有js回调函数名(大小写敏感)
//
//        Uri uri = Uri.parse(lowerCaseUrl);
//
//        String path = uri.getPath();
//
//        String ticket = PreferenceManager.getDefaultSharedPreferences(mActivity.getApplicationContext());
//
//        Map<String, String> cookies = new WeakHashMap<>();
//        cookies.put("Ticket", "");

//        view.loadUrl(url, cookies);

        // 当返回true时，控制网页在WebView中打开
        // 当返回false时，控制网页在系统自带的或第三方的浏览器中打开
        return super.shouldOverrideUrlLoading(view, url);
//        return true;
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);

        String lowerCaseUrl = url.toLowerCase().trim();

//        if (TaobaoUtils.isItemDetailsLink(lowerCaseUrl)) {
//            Uri uri = Uri.parse(lowerCaseUrl);
//            String itemId = uri.getQueryParameter("id");
//            if (mActivity instanceof GeneralWebViewActivity_) {
//                mToolbar.setToolbarTitle("商品详情");
//                ((GeneralWebViewActivity_) mActivity).enableItemSharing(itemId);
//            }
//        }else {
//            if (lowerCaseUrl.startsWith("http://") || lowerCaseUrl.startsWith("https://")) {
//                if (mActivity instanceof GeneralWebViewActivity_) {
//                    ((GeneralWebViewActivity_) mActivity).disableItemSharing();
//                }
//            }
//        }

//        // 隐藏输入法
//        Utils.UI.closeInputMethod(mActivity);
//
//        view.setFocusable(true);
//        view.setFocusableInTouchMode(true);
//        view.clearFocus();
//
//        if(!mWebView.getSettings().getLoadsImagesAutomatically()) {
//            mWebView.getSettings().setLoadsImagesAutomatically(true);
//        }

        String js = "var newscript = document.createElement(\"script\");";
        js += "newscript.src=\"https://app.menker.cn/App_Content/plugin/appjs.js\";";
        js += "document.body.appendChild(newscript);";
        view.loadUrl("javascript:" + js);
    }
}
